const Article = require('../../models/blog_article');
const Category = require('../../models/blog_category');
const Tag = require('../../models/blog_tags');
const ArticleCategory = require('../../models/article_category_tags');
const ArticleTalk = require('../../models/blog_article_talk');
const Utils = require('../../utils'); // 工具函数
// const Comment = require('../../models/blog_comment');

// const User = require('../../models/blog_user'); // 前台用户表
// const AdminUser = require('../../models/admin_users'); // 后台用户表
// const Role = require('../../models/admin_role'); // 后台角色

// const Utils = require('../../utils'); // 工具函数
// const authCodeFunc = require('../../utils/authCode');

const knex = require('../../models/knex');

const ControllerArticle = {
    // 获取列表
    getList: async function (req, res, next) {
        try {
            let { support, per_page, page, category_id, tag_id } = req.query;
            let offset = (per_page * (page - 1)) || 0; //计算当前页
            let articles = Article.table;
            let categorys = Category.table;

            let or = ArticleCategory.table;
            let list;

            const ass = await knex(or);
            const tags = await Tag.all();
            let articleIds = [];
            ass.forEach((v) => {
                if (category_id != 0 && v.category_id == category_id) {
                    articleIds.push(v.article_id)
                } else if (tag_id != 0) {
                    let tagIds = v.tag_ids.split(',');
                    let ask = tagIds.some(v => v == tag_id);
                    if (ask) articleIds.push(v.article_id)
                }
            })

            if (support == 1) { // 首页推荐时
                list = await knex(or)
                    .join(articles, function () {
                        this.on(`${articles}.id`, '=', `${or}.article_id`)
                            .andOn(`${articles}.status`, '=', 1)
                            .andOn(`${articles}.support`, '=', 1)
                    })
                    .join(categorys, `${or}.category_id`, '=', `${categorys}.id`)
                    .orderBy(`${articles}.sort`) //排序
                    .select(
                        `${articles}.id`, `${articles}.title`, `${articles}.summary`, `${articles}.image_url`, `${articles}.click`,
                        `${articles}.status`, `${articles}.support`, `${articles}.sort`, `${articles}.click`, `${articles}.created_time`,
                        `${categorys}.title as category_title`, `${categorys}.id as category_id`,
                        `${or}.tag_ids`
                    );
            } else if (articleIds.length <= 0 && support == 0) { // 文章页全部
                list = await knex(or)
                    .join(articles, function () {
                        this.on(`${articles}.id`, '=', `${or}.article_id`)
                            .andOn(`${articles}.status`, '=', 1)
                    })
                    .join(categorys, `${or}.category_id`, '=', `${categorys}.id`)
                    .limit(Number(per_page)).offset(Number(offset)) // 分页查询
                    .orderBy(`${articles}.sort`) //排序
                    .select(
                        `${articles}.id`, `${articles}.title`, `${articles}.summary`, `${articles}.image_url`, `${articles}.click`,
                        `${articles}.status`, `${articles}.support`, `${articles}.sort`, `${articles}.click`, `${articles}.created_time`,
                        `${categorys}.title as category_title`, `${categorys}.id as category_id`,
                        `${or}.tag_ids`
                    );

            } else if (articleIds.length > 0 && support == 0) { // 文章页点击分类/标签时
                list = await knex(or).whereIn('article_id', articleIds)
                    .join(articles, function () {
                        this.on(`${articles}.id`, '=', `${or}.article_id`)
                            .andOn(`${articles}.status`, '=', 1)
                    })
                    .join(categorys, `${or}.category_id`, '=', `${categorys}.id`)
                    .limit(Number(per_page)).offset(Number(offset)) // 分页查询
                    .orderBy(`${articles}.sort`) //排序
                    .select(
                        `${articles}.id`, `${articles}.title`, `${articles}.summary`, `${articles}.image_url`, `${articles}.click`,
                        `${articles}.status`, `${articles}.support`, `${articles}.sort`, `${articles}.click`, `${articles}.created_time`,
                        `${categorys}.title as category_title`, `${categorys}.id as category_id`,
                        `${or}.tag_ids`
                    );
            }

            // 标签名储存到文章列表中
            list.forEach((i) => {
                i.tag_name = []
                let ids = i.tag_ids.split(',');
                ids.forEach((v) => {
                    tags.forEach((n) => {
                        if (n.id == v) i.tag_name.push(n.title)
                    })
                })
            })

            res.json({ code: 200, msg: '链接成功', data: { list } })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },

    // 获取详情
    getById: async function (req, res, next) {
        try {
            const { id } = req.query;
            const or = ArticleCategory.table;
            const article = Article.table;
            const category = Category.table;
            const prev = await knex(article).where('id', '<', id).orderBy('id', 'desc');
            const next = await knex(article).where('id', '>', id).orderBy('id', 'first');
            const list = await knex(or).where({ article_id: id })
                .join(article, `${or}.article_id`, `${article}.id`)
                .join(category, `${or}.category_id`, `${category}.id`)
                .select(
                    `${article}.id`,
                    `${article}.title`,
                    `${article}.summary`,
                    `${article}.click`,
                    `${article}.content`,
                    `${article}.created_time`,
                    `${category}.id as category_id`,
                    `${category}.title as category_title`,
                    `${or}.tag_ids`,
                )
            const tag_ids = list[0].tag_ids.split(',').map(Number);
            const tags = await Tag.batchSelect(tag_ids);
            list[0].tags = tags;

            res.json({ code: 200, msg: '链接成功', data: { list: list[0], prev: prev[0], next: next[0] } })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
    // 获取评论列表
    getCommentList: async function (req, res, next) {
        try {
            const { id, per_page, page } = req.query;
            const all = await ArticleTalk.select({ article_id: id });

            if (all.length <= 0) return res.json({ code: 200, msg: '暂无评论', data: {} })

            const getComment = Utils.getData(all); //* 树形数据处理索引0为一级，其他均为子级
            const commentData = Utils.getChildrenTree(getComment, getComment[0]); //* 按父子关系处理分类
            const list = Utils.getPagination(commentData, per_page, page);

            list.sort((a, b) => {
                return a.id - b.id
            })

            res.json({ code: 200, msg: '连接成功', data: { list, total: commentData.length } })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
    // 添加评论
    InsertComment: async function (req, res, next) {
        try {
            let { id, articleId, content, name, mail, url } = req.body;
            let params = { article_id: articleId, content: encodeURI(content), name, created_time: new Date().getTime() };

            if (!content) return res.json({ code: 0, msg: '回复内容必须填写' });
            if (!name) return res.json({ code: 0, msg: '必须填写昵称' });
            if (mail) params.mail = mail;
            if (url) params.url = url;

            if (id) {
                const item = await ArticleTalk.select({ id })
                params.pid = item[0].pid ? item[0].pid : id;
                params.reply_id = id;
                params.reply_name = item[0].name;
                params.reply_content = item[0].content;
                params.reply_master = item[0].master;
            }

            await ArticleTalk.insert(params);

            res.json({ code: 200, msg: '评论成功', data: {} })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },

    // // 纪录点击
    // clickRecord: async function (req, res, next) {
    //     try {
    //         let { id } = req.query;

    //         const articles = await Article.select({ id });

    //         await Article.update(id, { click: articles[0].click + 1 })

    //         res.json({ code: 200, msg: '链接成功' })
    //     } catch (e) {
    //         res.json({ code: 0, data: e })
    //     }
    // },

    // commentList: async function (req, res, next) {
    //     try {
    //         let { id, per_page, page } = req.query;
    //         let users = User.table;
    //         let adUser = AdminUser.table;
    //         let roles = Role.table;
    //         let comments = Comment.table;

    //         let admin = await knex(comments)
    //             .join(adUser, `${comments}.user_id`, `${adUser}.id`)
    //             .join(roles, `${comments}.role`, `${roles}.id`)
    //             .select(
    //                 `${comments}.id`,
    //                 `${comments}.comment_level`,
    //                 `${comments}.parent_comment_id`,
    //                 `${comments}.reply_comment_id`,
    //                 `${comments}.content`,
    //                 `${comments}.role`,
    //                 `${comments}.host`,
    //                 `${comments}.user_id`,
    //                 `${comments}.created_time`,
    //                 `${adUser}.user_name`,
    //                 `${adUser}.user_account as account`,
    //                 `${adUser}.user_avatar_url as avatar`,
    //                 `${roles}.name as role_name`,
    //             )
    //             .whereRaw(`${comments}.article_id = ${id}`)

    //         let web = await knex(comments)
    //             .join(users, `${comments}.user_id`, `${users}.id`)
    //             .select(
    //                 `${comments}.id`,
    //                 `${comments}.comment_level`,
    //                 `${comments}.parent_comment_id`,
    //                 `${comments}.reply_comment_id`,
    //                 `${comments}.content`,
    //                 `${comments}.role`,
    //                 `${comments}.host`,
    //                 `${comments}.user_id`,
    //                 `${comments}.created_time`,
    //                 `${users}.name as user_name`,
    //                 `${users}.account`,
    //                 `${users}.avatar_url as avatar`,
    //             )
    //             .whereRaw(`${comments}.article_id = ${id}`)

    //         // admin与web合并
    //         const newComment = admin.concat(web);

    //         // 按id升序排序
    //         newComment.sort((a, b) => {
    //             return a.id - b.id
    //         });

    //         const getComment = Utils.getData(newComment); // 树形数据处理索引0为一级，其他均为子级
    //         const commentData = Utils.getChildrenTree(getComment, getComment[0]); // 按父子关系处理分类
    //         const list = Utils.getPagination(commentData, per_page, page);

    //         let total = commentData.length; // 文章总数
    //         let number = Math.ceil(total / per_page); // 计算出信息总页数

    //         res.json({ code: 200, msg: '连接成功', data: { list, total, number } })
    //     } catch (e) {
    //         res.json({ code: 0, data: e })
    //     }
    // },

    // /* 评论 */
    // comment: async function (req, res, next) {
    //     try {
    //         let { content, comment_level, article_id } = req.body;
    //         let authorization = req.headers.authorization;
    //         let user_id = '';

    //         if (authorization) {
    //             let token = authorization.split(' ');
    //             let user_decode = authCodeFunc(token[1], 'DECODE');
    //             let user_info = user_decode.str.split('\t');
    //             user_id = user_info[0];
    //         } else {
    //             return res.json({ code: 0, msg: '还未登录' })
    //         }

    //         let params = {
    //             user_id,
    //             content: encodeURI(content),
    //             comment_level,
    //             article_id,
    //             created_time: new Date().getTime()
    //         }

    //         await Comment.insert(params);

    //         res.json({ code: 200, msg: '评论成功', data: {} })
    //     } catch (e) {
    //         res.json({ code: 0, data: e })
    //     }
    // },

    // /* 回复 */
    // reply: async function (req, res, next) {
    //     try {
    //         let { id, article_id, content, comment_level } = req.body;
    //         let authorization = req.headers.authorization;
    //         let user_id = '';

    //         if (authorization) {
    //             let token = authorization.split(' ');
    //             let user_decode = authCodeFunc(token[1], 'DECODE');
    //             let user_info = user_decode.str.split('\t');
    //             user_id = user_info[0];
    //         } else {
    //             return res.json({ code: 0, msg: '还未登录' })
    //         }

    //         const comments = await Comment.select({ id });
    //         let parent_comment_id = comments[0].parent_comment_id; // 父留言id
    //         let reply_comment_id = id;

    //         let params = {
    //             user_id,
    //             article_id,
    //             content: encodeURI(content),
    //             comment_level,
    //             parent_comment_id: parent_comment_id ? parent_comment_id : id,
    //             reply_comment_id,
    //             created_time: new Date().getTime()
    //         }

    //         await Comment.insert(params);

    //         res.json({ code: 200, msg: '评论成功', data: {} })
    //     } catch (e) {
    //         res.json({ code: 0, data: e })
    //     }
    // },
}

module.exports = ControllerArticle;
